package com.bdqn.ch07.controller;

import com.bdqn.ch07.entity.User;
import com.bdqn.ch07.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

@Controller
public class LoginController {

    @Resource
    UserService userService;


    //配置欢迎页面
    @RequestMapping("/")
    public String index(Model model, HttpServletResponse response) {
        return "login";
    }

    @RequestMapping("/login")
    public String login() {
        return "login";
    }

    @RequestMapping("/logout")
    public String logout(HttpSession session) {
        //清空session
        session.removeAttribute("sessionuser");
        return "login";
    }

    @RequestMapping("/main")
    public String main() {
        return "main";
    }


    @PostMapping(value = "/dologin")
    public String dologin(@RequestParam(value = "usrName") String usrName,
                          @RequestParam(value = "usrPassword") String usrPassword,
                          Model model,
                          HttpSession session) {
        //User user = userService.findByUserNameBiz(usrName);
        /*if (user == null) {
            model.addAttribute("msg", "用户名不存在");
            return "login";
        } else {
            if (!user.getUsrPassword().equals(usrPassword)) {
                model.addAttribute("msg", "密码错误");
                return "login";
            } else {
                session.setAttribute("sessionuser", user);
                return "main";
            }
        }*/
        try {
            //通过用户名和密码产生shiro token
            UsernamePasswordToken token = new UsernamePasswordToken(usrName, usrPassword);
            Subject subject = SecurityUtils.getSubject();
            subject.login(token);//认证、登录。通过主体调用自定义realm调用MyShiroRealm  doGetAuthenticationInfo 认证方法
            //如果没有出现异常认证(登录)成功
            User user = (User) subject.getPrincipal();
            session.setAttribute("sessionuser", user);
            return "redirect:/main";//建议重定向
        } catch (UnknownAccountException e) {
            model.addAttribute("msg", "用户名错误，登录失败！");
            return "login";
        } catch (IncorrectCredentialsException e) {
            model.addAttribute("msg", "密码错误，登录失败！");
            return "login";
        } catch (LockedAccountException e) {
            model.addAttribute("msg", "用户被禁用，登录失败！");
            return "login";
        } catch (AuthenticationException e) {
            model.addAttribute("msg", "认证异常，登录失败！");
            return "login";
        }
    }

}
